import { NextRequest, NextResponse } from 'next/server';
import {
  ChatSessionOperations,
  ChatMessageOperations,
} from '@/lib/database-operations';
import { getOptimizedDeepSeekClient } from '@/lib/deepseek';
import { ConversationContextManager } from '@/lib/conversation-context';
import { enhancedRAG } from '@/lib/enhanced-rag';
import { intentRecognitionService } from '@/lib/intent-recognition';
import { HumanMessage, SystemMessage } from '@langchain/core/messages';
import { v4 as uuidv4 } from 'uuid';
import { embeddingModel, qdrantClient } from '@/lib/vectorization';

// 初始化对话上下文管理器
const contextManager = new ConversationContextManager();

// 向量搜索函数
async function vectorSearch(
  query: string,
  limit: number = 5,
  threshold: number = 0.7
) {
  try {
    const queryEmbedding = await embeddingModel.embedQuery(query);

    const searchResult = await qdrantClient.search('documents', {
      vector: queryEmbedding,
      limit,
      score_threshold: threshold,
      with_payload: true,
    });

    return searchResult.map((result: any) => ({
      id: result.id,
      score: result.score || 0,
      content: result.payload?.content || '',
      title: result.payload?.title || '',
      document_id: result.payload?.document_id || '',
      chunk_index: result.payload?.chunk_index || 0,
    }));
  } catch (error) {
    console.error('向量搜索失败:', error);
    return [];
  }
}

// 流式聊天API
export async function POST(request: NextRequest) {
  try {
    const { message, sessionId, userId, useRAG = true } = await request.json();

    if (!message?.trim()) {
      return NextResponse.json(
        { success: false, error: '消息不能为空' },
        { status: 400 }
      );
    }

    // 创建可读流
    const encoder = new TextEncoder();
    const stream = new ReadableStream({
      async start(controller) {
        try {
          let currentSessionId = sessionId;

          // 如果没有会话ID，创建新会话
          if (!currentSessionId) {
            currentSessionId = await ChatSessionOperations.create(
              message.slice(0, 50) + (message.length > 50 ? '...' : ''),
              userId
            );

            // 发送会话ID
            controller.enqueue(
              encoder.encode(
                `data: ${JSON.stringify({
                  type: 'session_created',
                  session_id: currentSessionId,
                })}\n\n`
              )
            );
          }

          // 保存用户消息
          const userMessageId = await ChatMessageOperations.create({
            session_id: currentSessionId,
            role: 'user',
            content: message,
            created_at: new Date().toISOString(),
            metadata: {
              timestamp: Date.now(),
              use_rag: useRAG,
            },
          });

          controller.enqueue(
            encoder.encode(
              `data: ${JSON.stringify({
                type: 'user_message_saved',
                message_id: userMessageId,
              })}\n\n`
            )
          );

          // 获取会话历史消息
          const existingMessages =
            await ChatMessageOperations.getBySessionId(currentSessionId);

          let ragResults: any[] = [];

          if (useRAG) {
            // 发送搜索状态
            controller.enqueue(
              encoder.encode(
                `data: ${JSON.stringify({
                  type: 'searching',
                  message: '正在搜索相关文档...',
                })}\n\n`
              )
            );

            // 使用增强的RAG系统进行智能检索
            const retrievalResult = await enhancedRAG.intelligentRetrieval(
              message,
              existingMessages,
              userId
            );

            ragResults = retrievalResult.results.map(result => ({
              title: result.title || '未知',
              content: result.content || '',
              similarity: result.score,
            }));

            // 发送搜索结果
            controller.enqueue(
              encoder.encode(
                `data: ${JSON.stringify({
                  type: 'search_results',
                  results: ragResults,
                })}\n\n`
              )
            );
          }

          // 发送生成状态
          controller.enqueue(
            encoder.encode(
              `data: ${JSON.stringify({
                type: 'generating',
                message: '正在生成回答...',
              })}\n\n`
            )
          );

          // 构建对话上下文（包含意图识别）
          const conversationContext = await contextManager.buildContext(
            existingMessages,
            message,
            ragResults.map(r => r.content).join('\n'),
            userId
          );

          // 根据意图和RAG状态选择最优的DeepSeek配置
          let modelPreset: 'conversational' | 'rag' | 'creative' | 'analytical' | 'concise' = 'conversational';
          if (useRAG) {
            modelPreset = 'rag';
          } else if (conversationContext.contextInfo.intentResult) {
            // 根据意图类型选择模型配置
            switch (conversationContext.contextInfo.intentResult.intent) {
              case 'creative':
                modelPreset = 'creative';
                break;
              case 'analysis':
                modelPreset = 'analytical';
                break;
              case 'instruction':
              case 'help':
                modelPreset = 'concise';
                break;
              default:
                modelPreset = 'conversational';
            }
          }

          const deepseekClient = getOptimizedDeepSeekClient(modelPreset);

          // 准备消息
          const messages = [
            ...conversationContext.messages,
          ];

          // 流式生成响应
          const stream = await deepseekClient.stream(messages);
          let fullResponse = '';

          for await (const chunk of stream) {
            const content = chunk.content;
            if (content) {
              fullResponse += content;
              controller.enqueue(
                encoder.encode(
                  `data: ${JSON.stringify({
                    type: 'content',
                    content: content,
                  })}\n\n`
                )
              );
            }
          }

          // 保存AI响应
          const aiMessageId = await ChatMessageOperations.create({
            session_id: currentSessionId,
            role: 'assistant',
            content: fullResponse,
            created_at: new Date().toISOString(),
            metadata: {
              timestamp: Date.now(),
              rag_results: ragResults,
              context_used: useRAG && ragResults.length > 0,
            },
          });

          // 更新用户画像（如果有意图识别结果）
          if (
            conversationContext.contextInfo.intentResult &&
            conversationContext.contextInfo.responseStrategy &&
            userId
          ) {
            intentRecognitionService.updateUserProfile(
              userId,
              conversationContext.contextInfo.intentResult.intent,
              conversationContext.contextInfo.responseStrategy
            );
          }

          // 发送完成信号
          controller.enqueue(
            encoder.encode(
              `data: ${JSON.stringify({
                type: 'completed',
                session_id: currentSessionId,
                user_message_id: userMessageId,
                ai_message_id: aiMessageId,
                rag_results: useRAG ? ragResults : undefined,
                context_used: useRAG && ragResults.length > 0,
              })}\n\n`
            )
          );

          controller.enqueue(encoder.encode('data: [DONE]\n\n'));
          controller.close();
        } catch (error) {
          console.error('流式聊天处理失败:', error);
          controller.enqueue(
            encoder.encode(
              `data: ${JSON.stringify({
                type: 'error',
                error: '聊天处理失败',
              })}\n\n`
            )
          );
          controller.close();
        }
      },
    });

    return new Response(stream, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST',
        'Access-Control-Allow-Headers': 'Content-Type',
      },
    });
  } catch (error) {
    console.error('流式聊天初始化失败:', error);
    return NextResponse.json(
      { success: false, error: '流式聊天初始化失败' },
      { status: 500 }
    );
  }
}
